package com.example.juc.demobase;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class CountDownLatchDemo {


    public static void main(String[] args) throws InterruptedException {

        //创建CountDownLatch countDownLatch = new CountDownLatch(6);设置初始值
        CountDownLatch countDownLatch = new CountDownLatch(6);
        for (int i = 1; i <= 6; i++) {

            int finalI = i;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + "离开教室 " + finalI);
                    countDownLatch.countDown();
                }
            }, "Thread-" + i).start();

        }

        countDownLatch.await();
        System.out.println("main end...down 班长锁门");

    }

}


class CycliBarrierDemo {

    public static void main(String[] args) {

        //创建CycliBarrier cycliBarrier = new CycliBarrier(6);

        CyclicBarrier cyclicBarrier =
                new CyclicBarrier(7, new Runnable() {
                    @Override
                    public void run() {
                        System.out.println("班上所有龙珠都到齐了，开课");
                    }
                });

        for (int j = 1; j <= 7; j++) {
            int finalJ = j;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        System.out.println(Thread.currentThread().getName() + " 等待龙珠"+ finalJ);
                        cyclicBarrier.await();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }, "Thread-" + j).start();
        }
            }

}

class  SemaphoreDemo{

    public static void main(String[] args) throws InterruptedException {
        Semaphore semaphore = new Semaphore(3);
        for (int i = 1; i <= 6; i++) {
            int finalI = i;
            int finalI1 = i;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        semaphore.acquire();
                        System.out.println(Thread.currentThread().getName() + "获取到许可，开始学习");
                        TimeUnit.SECONDS.sleep(new Random().nextInt(5));
                        System.out.println(Thread.currentThread().getName()+ finalI1 +"离开了车位");
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    finally {
                        semaphore.release();
                    }
                }
            },"Thread"+i).start();
        }
    }

}
